package com.lhdx.practical.utils;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 生成唯一ID
 * @author Snake
 *
 */
public final class IDGenerator {
    private static int ID_LEN = 8;
    private static IDGenerator generator = new IDGenerator();
    protected static Format fmat = new SimpleDateFormat("yyyyMMddhh");

    /**
     * private and only constructor
     */
    private IDGenerator() {
    }

    /**
     * @return Generator
     */
    public static IDGenerator getInstance() {
        if (generator == null)
            generator = new IDGenerator();
        return generator;
    }

    /**
     * @return the iD
     * 线下测试自动生成ID
     */
    public static long getID() {
        int root = (int) Math.pow(10, ID_LEN);
        int id = 0;
        do {
            long tmp = Math.abs(Double.doubleToLongBits(Math.random()));
            id = (int) (tmp % root);
        } while (id < (root / 10));
        Date date = new Date();
        return Long.parseLong(fmat.format(date) + "" +  id);
    }

    /**
     * @return the iD_LEN
     */
    public static int getID_LEN() {
        return ID_LEN;
    }

    /**
     * @param iD_LEN
     *            the iD_LEN to set
     */
    public static void setID_LEN(int iD_LEN) {
        ID_LEN = iD_LEN;
    }
}